<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
    <script src="../js/axios.js"></script>
</head>
<body>
<div id="root">
    <h1>hello {{userName}}</h1>
    <input type="text" v-model="sendMsg" placeholder="请输入需要发送的信息">
    <button @click="wsSendMessage">发送webSocket信息</button>
    <div>客户端接收到的消息:</div>
    <ul>
        <li v-for="(data,index) in serverMsg" :key="index">{{data}}</li>
    </ul>
</div>
<script>
    Vue.config.productionTip = false
    new Vue({
        el: '#root',
        data() {
            return {
                sendMsg: '',
                ws: null,
                wsUrl: 'ws://localhost:8080/websocket',
                url: 'http://localhost:8080/websocket/getUserName',
                userName: '',
                serverMsg: []
            }
        },
        created() {
            this.getUserName()
        },
        methods: {
            getUserName() {
                axios.get(this.url).then(
                    response => {
                        this.initWebSocket(response.data.msg)
                    },
                    error => {
                        console.log(error)
                    }
                )
            },
            // 初始化websocket
            initWebSocket(userName) {
                if ('WebSocket' in window) {
                    this.userName = userName
                    this.ws = new WebSocket(this.wsUrl + '/' + userName)
                    this.ws.onopen = this.wsOnOpen
                    this.ws.onerror = this.wsOnError
                    this.ws.onmessage = this.wsOnMessage
                    this.ws.onclose = this.wsOnClose
                } else {
                    console.log('您的浏览器不支持WebSocket')
                }
            },
            // 打开连接
            wsOnOpen() {
                console.log('和服务器连上了')
            },
            // 接收信息
            wsOnMessage(data) {
                console.log('客户端接收到消息了', data.data)
                this.serverMsg.unshift(data.data)
            },
            // 关闭连接
            wsOnClose() {
                console.log('和服务器断开连接了');
            },
            // 监听错误事件
            wsOnError(error) {
                console.log('websocket通讯过程发生异常', error);
            },
            // 发送消息给服务器端
            wsSendMessage() {
                this.ws.send(JSON.stringify(this.sendMsg))
            }

        }

    })
</script>
</body>
</html>